package com.sevennotes.classtable.utils

import com.sevennotes.classtable.config.Config
import com.sevennotes.classtable.model.Time
import java.text.SimpleDateFormat
import java.util.*

object TimeUtil {
    private fun addTime(startHour: Int, startMin: Int, addMin: Int): Pair<Int, Int> {
        val c = Calendar.getInstance()
        c.set(Calendar.HOUR_OF_DAY, startHour)
        c.set(Calendar.MINUTE, startMin)
        c.add(Calendar.MINUTE, addMin)
        return Pair(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE))
    }

    fun addTime(oldTime: Time, addMin: Int): Time {
        val newTime = addTime(oldTime.startHour, oldTime.startMin, addMin)
        return Time(newTime.first, newTime.second)
    }

    fun todayLast(): Date {
        val c1 = Calendar.getInstance()
        c1.set(Calendar.HOUR_OF_DAY, 23)
        c1.set(Calendar.MINUTE, 59)
        c1.set(Calendar.SECOND, 59)
      return c1.time
    }

    fun dateToTime(date: Date): Time {
        val c = Calendar.getInstance()
        c.time = date
        return Time(
            c.get(Calendar.HOUR_OF_DAY),
            c.get(Calendar.MINUTE)
        )
    }

    //返回今年1月1日0点0时0分的时间节点
    fun currentYear(): Date {
        val c = Calendar.getInstance()
        c.set(c.get(Calendar.YEAR),0,1,0,0,0)
        return c.time
    }

    fun currentWeekDay(date: Date = Date()): Int {
        val c = Calendar.getInstance()
        c.time = date
        val day = c.get(Calendar.DAY_OF_WEEK)
        return if (day == 1) 6 else day - 2
    }

    fun conversionTimeToString(
        startTime: Time,
        duration: Int,
        weekDay: Int,
        withWeekDay: Boolean = true
    ): String {
        val minStr = getMinString(startTime.startMin)
        val endTime = addTime(startTime, duration)
        val weekText = if (withWeekDay) "${Config.weekdays[weekDay]}  " else ""
        return "${weekText}${startTime.startHour} : $minStr  - ${endTime.startHour} : ${getMinString(endTime.startMin)}"
    }

    fun formatDate(date: Date, pattern: String = "yyyy年MM月dd日"): String {
        val df = SimpleDateFormat(pattern, Locale.CHINA)
        return df.format(date)
    }

    fun radomDate(): Date {
        val c = Calendar.getInstance()
        val now = c.timeInMillis
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
        val date = df.parse("2000-1-1 00:00:00")
        val before = date!!.time
        val r = Random()
        val randomdate = before + (r.nextFloat() * (now - before + 1)).toLong()
        return Date(randomdate)
    }

    private fun getMinString(min: Int): String {
        return if (min >= 10) min.toString() else "0$min"
    }
}